import machine,time,_thread,socket,network
from machine import Pin,PWM,uart

led1=Pin(2,Pin.OUT)
led1.value(1)
led2=PWM(Pin(3))
led2.freq(60)
led2.duty(512)
#指示灯
motor=PWM(Pin(4))
motor.freq(1000)
motor.duty(512)
#旋转电机初始化
spin_way=ADC(Pin(34))
spin_way.atten(ADC.ATTN_11DB)
#旋转角度传感器初始化
TRIG=Pin(5,Pin.OUT)
ECHO=Pin(18,Pin.IN)
#超声波传感器初始化
speed_of_sound=0.0343

ap=network.WLAN(network.AP_IF)
ap.config(essid='RADAR',password='123456787654321')
ap.active(True)
print('AP is running')

uart=uart.UART(1,115200,tx=Pin(17),rx=Pin(16))
uart.init(115200,tx=Pin(17),rx=Pin(16))
print('UART is running')
uart.write('READR OFF')
#串口初始化
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('0.0.0.0',100))
s.listen(5)
uart_data = uart.read()
if uart_data:
    conn.send(uart_data)

# 转发流程：网络→串口
wifi_data = conn.recv(1024)
if wifi_data:
    uart.write(wifi_data)
#wifi串口
def angle():
    angle_adc=spin_way.read()
    angle=(angle_adc-4095)*0.0805
    return angle

def measure_distance():
    """
    使用超声波传感器测量距离
    返回值：距离（厘米）
    """
    # 发送10μs的高电平触发信号
    TRIG.value(0)
    time.sleep_us(2)
    TRIG.value(1)
    time.sleep_us(10)
    TRIG.value(0)
    
    # 等待回响信号变为高电平
    while ECHO.value() == 0:
        pass
    start_time = time.ticks_us()  # 记录开始时间
    
    # 等待回响信号变为低电平
    while ECHO.value() == 1:
        pass
    end_time = time.ticks_us()  # 记录结束时间
    
    # 计算持续时间（μs）
    duration = time.ticks_diff(end_time, start_time)
    
    # 计算距离：距离 = (时间 × 声速) / 2
    distance = (duration * speed_of_sound) / 2
    
    return distance

while True:
    angle=angle()
    uart.write(angle(),measure_distance())
    print(angle(),measure_distance())
    #主循环
    if uart.read() == 'READR STOP':
        motor.duty(0)
        print('motor stop')
        led2.freq(1000)
        break

